package com.syun.quartz.example;

import org.quartz.JobDataMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api")
public class QuartzJobController {


    @Autowired
    private QuartzJobService quartzJobService;

    @GetMapping("get")
    public List<QuartzBean> getQuartzList() throws Exception{
        return quartzJobService.getScheduleJobList();
    }

    @GetMapping("createSimpleJob")
    public String createSimpleJob(String jobName,String jobGroup, String jobDescription) throws Exception {
        QuartzBean quartzBean = new QuartzBean();
        quartzBean.setJobClass("com.syun.quartz.example.MyJob");
        quartzBean.setJobName(jobName);
        quartzBean.setJobGroup(jobGroup);
        quartzBean.setJobDescription(jobDescription);
        JobDataMap map = new JobDataMap();
        map.put("serviceId", "1001");
        quartzBean.setJobDataMap(map);
        // 保存10s中后开始，50s后结束，每隔3秒钟一次
        Calendar newTimeStart = Calendar.getInstance();
        newTimeStart.setTime(new Date());
        newTimeStart.add(Calendar.SECOND,10);
        quartzBean.setStartTime(newTimeStart.getTime());

        Calendar newTimeEnd = Calendar.getInstance();
        newTimeEnd.setTime(new Date());
        newTimeEnd.add(Calendar.SECOND,50);
        quartzBean.setStartTime(newTimeEnd.getTime());

        quartzBean.setInterval(3);
        quartzJobService.createScheduleSimpleJob(quartzBean);
        return "SUCCESS";
    }

    @GetMapping("/createCronJob")
    public String createCronJob(String jobName,String jobGroup,String jobDescription) throws Exception{
        QuartzBean quartzBean = new QuartzBean();
        quartzBean.setJobClass("com.syun.quartz.example.MyJob");
        quartzBean.setJobName(jobName);
        quartzBean.setJobGroup(jobGroup);
        quartzBean.setJobDescription(jobDescription);
        quartzBean.setCronExpression("*/10 * * * * ?");
        JobDataMap map = new JobDataMap();
        map.put("serviceId", "1001");
        quartzBean.setJobDataMap(map);
        quartzJobService.createScheduleCronJob(quartzBean);
        return "SUCCESS";
    }


    @GetMapping(value = "/delete")
    public String delete(String jobName,String jobGroup) throws Exception{
        quartzJobService.deleteScheduleJob(jobName, jobGroup);
        return "SUCCESS";
    }

    @GetMapping(value = "check")
    public String check(String jobName, String jobGroup) throws Exception {
        if(quartzJobService.checkExistsScheduleJob(jobName, jobGroup)){
            return "存在定时任务："+jobName;
        }else{
            return "不存在定时任务："+jobName;
        }
    }
}
